package com.zhiche.lisa.lspm.service.fleet.impl;

import java.util.*;

import com.zhiche.lisa.core.enums.TableStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.zhiche.lisa.core.enums.FleetResourcesEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.lspm.dao.mapper.driver.DriverMapper;
import com.zhiche.lisa.lspm.dao.mapper.fleet.FleetBindMapper;
import com.zhiche.lisa.lspm.dao.mapper.fleet.FleetDriverMapper;
import com.zhiche.lisa.lspm.dao.mapper.fleet.FleetMapper;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierInfo;
import com.zhiche.lisa.lspm.dao.model.carrier.bo.CarrierInfoLineBO;
import com.zhiche.lisa.lspm.dao.model.driver.Driver;
import com.zhiche.lisa.lspm.dao.model.driver.bo.DriverLineBO;
import com.zhiche.lisa.lspm.dao.model.fleet.Fleet;
import com.zhiche.lisa.lspm.dao.model.fleet.FleetBind;
import com.zhiche.lisa.lspm.dao.model.fleet.FleetBindLog;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerInfo;
import com.zhiche.lisa.lspm.dao.model.trailer.bo.TrailerInfoLineBO;
import com.zhiche.lisa.lspm.service.carrier.ICarrierInfoService;
import com.zhiche.lisa.lspm.service.driver.IDriverService;
import com.zhiche.lisa.lspm.service.fleet.IFleetBindLogService;
import com.zhiche.lisa.lspm.service.fleet.IFleetDriverService;
import com.zhiche.lisa.lspm.service.trailer.TrailerInfoService;
import com.zhiche.lisa.lspm.service.utils.UaaUtil;
import com.zhiche.lisa.lspm.vo.common.AccountVO;
import com.zhiche.lisa.lspm.vo.driver.DriverBasicVO;

/**
 * 	车队司机，牵引车，挂车登记业务实现
 * @author fanguangji
 * @since 2018-11-07
 */
@Service
public class FleetDriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements IFleetDriverService{

	private static final Logger LOGGER = LoggerFactory.getLogger(IDriverService.class);
	
	@Autowired private FleetDriverMapper fleetDriverMapper;
	@Autowired private UaaUtil uaaUtil;
	@Autowired private FleetBindMapper fleetBindMapper;
	@Autowired private FleetMapper fleetMapper;
	@Autowired private ICarrierInfoService carrierInfoService;
	@Autowired private IDriverService driverService;
	@Autowired private TrailerInfoService trailerInfoService;
	@Autowired private IFleetBindLogService fleetBindLogService;
	@Autowired private IFleetBindLogService iFleetBindLogService;
	
	/**
	 * 查看车队司机列表
	 */
	@Override
	public Page<Map<String,Object>> driverLine(Page<DriverLineBO> page) {
		
		Map<String,Object> condition = page.getCondition();
		if(null == condition) return null;

		//  车队id切割成集合
		String fleetId = (String)condition.get("fleetId"); 
		if(StringUtils.isEmpty(fleetId)) return null;
			
		List<String> fleetIds = Arrays.asList(fleetId.split(","));
		condition.put("fleetIds", fleetIds);
		
		Page<Map<String,Object>> pageVo = new Page<>();
//		List<Map<String,Object>> list = baseMapper.driverLine(page, ew);
	    BeanUtils.copyProperties(page, pageVo);
	    pageVo.setRecords(fleetDriverMapper.selectFleetDriver(condition,pageVo));
	    return pageVo;
	}

	
	 /**
     * 	添加或更新司机基本信息
     *
     * @param driver 司机信息
     * @param authorization 验证信息
     * @return Driver
     */
    @Override
    @Transactional
	public Driver updateDriver(DriverBasicVO driver, String authorization) {
    	try {
			Long fleetId = driver.getFleetId();
			driver.setFleetId(null);
    		Driver driverResult = driverService.updateDriver(driver, authorization);
            
            // 添加车队与司机关系
            if(Objects.isNull(fleetId)) throw new BaseException("车队不能为空！");
            
            Wrapper<FleetBind> wrapper = new EntityWrapper<>();
            wrapper.eq("fleet_id", fleetId).eq("resource_id", driverResult.getId())
					.eq("resource_type", TableStatusEnum.STATUS_03.getCode());
            
            List<FleetBind> fleetBinds = fleetBindMapper.selectList(wrapper);
            
            if(fleetBinds.size() > 1) throw new BaseException("车队与司机关系存在多条！");
            // 不存在添加
            if(fleetBinds.size() == 0) {
            	FleetBind fleetBind = new FleetBind();
            	fleetBind.setFleetId(fleetId);
            	fleetBind.setResourceId(driverResult.getId());
            	fleetBind.setResourceType(FleetResourcesEnum.DRIVER.getCode());
            	fleetBind.setGmtCreate(new Date());
            	fleetBind.setGmtModify(new Date());
            	fleetBind.setCreator(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
            	
            	fleetBindMapper.insert(fleetBind);
				// 添加日志
				FleetBindLog fleetBindLog = new FleetBindLog();
				BeanUtils.copyProperties(fleetBind, fleetBindLog);
				iFleetBindLogService.insert(fleetBindLog);
            }else {
            	// 存在只有一条,修改
            	for (FleetBind fleetBind : fleetBinds) {
            		// 车队修改进行关系修改,入口是资源入口所以资源不变
            		if(!fleetBind.getFleetId().equals(fleetId)) {
            			// 记录日志
            			FleetBindLog fleetBindLog = new FleetBindLog();
            			BeanUtils.copyProperties(fleetBind, fleetBindLog, "id","gmtCreate");
            			fleetBindLogService.insert(fleetBindLog);
            			// 修改
            			fleetBind.setFleetId(fleetId);
//            			fleetBind.setResourceId(driverResult.getId());
            			fleetBindMapper.updateById(fleetBind);
            		}
				}
			}
            
            return driverResult;
            
        } catch (BaseException e) {
            LOGGER.error("FleetDriverServiceImpl.updateDriver" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("FleetDriverServiceImpl.updateDriver" + e.getMessage());
            throw new BaseException("司机信息保存失败");
        }
	}


	/**
	 * 查看登陆人员所有车队
	 */
	@Override
	public List<Fleet> selectFleetInfo(String fleetId, String authorization) {
		if(null != fleetId && !"".equals(fleetId)) {
			List<String> fleetIds = Arrays.asList(fleetId.split(","));
			List<Fleet> fleets = fleetMapper.selectBatchIds(fleetIds);
			return fleets;
		}
		return null;
	}


	/**
	 * 获取车队牵引车列表
	 */
	@Override
	public Page<Map<String, Object>> carrierInfoLine(Page<CarrierInfoLineBO> page, String authorization) {
		
		Map<String,Object> condition = page.getCondition();
		Page<Map<String,Object>> pageVo = new Page<>();
		if(null == condition) return null;
		
		//  车队id切割成集合
		String fleetId = (String)condition.get("fleetId"); 
		if(StringUtils.isEmpty(fleetId)) return null;
		
		List<String> fleetIds = Arrays.asList(fleetId.split(","));
		condition.put("fleetIds", fleetIds);
		
		BeanUtils.copyProperties(page, pageVo);
		
		List<Map<String,Object>> list = fleetDriverMapper.selectFleetCarrier(condition,pageVo);
		list.forEach(carrierInfoLineVO -> {
            if (!Strings.isNullOrEmpty((String)carrierInfoLineVO.get("creator"))) {
                AccountVO accountVO = uaaUtil.getAccountById((String)carrierInfoLineVO.get("creator"), authorization);
                if (Objects.nonNull(accountVO)) {
                    carrierInfoLineVO.put("creator",accountVO.getIdentifier());
                }
            }
        });
	    pageVo.setRecords(list);
	    
	    return pageVo;
	}


    /**
     * 车队添加或修改牵引车
     */
    @Transactional
	@Override
	public CarrierInfo updateCarrier(CarrierInfo carrierInfo) {
    	try {
			Long fleetId = carrierInfo.getFleetId();
			carrierInfo.setFleetId(null);
    		CarrierInfo carrierInfoNew = carrierInfoService.updateCarrier(carrierInfo);
        	// 添加车队与牵引车关系
            if(Objects.isNull(fleetId)) throw new BaseException("车队不能为空！");
            
            Wrapper<FleetBind> wrapper = new EntityWrapper<>();
            wrapper.eq("fleet_id", fleetId).eq("resource_id", carrierInfo.getId());
            
            List<FleetBind> fleetBinds = fleetBindMapper.selectList(wrapper);
            
            if(fleetBinds.size() > 1) throw new BaseException("车队与该牵引车关系存在多条！");
            // 不存在添加
            if(fleetBinds.size() == 0) {
            	FleetBind fleetBind = new FleetBind();
            	fleetBind.setFleetId(fleetId);
            	fleetBind.setResourceId(carrierInfo.getId());
            	fleetBind.setResourceType(FleetResourcesEnum.CARRIER.getCode());
				fleetBind.setGmtCreate(new Date());
				fleetBind.setGmtModify(new Date());
            	fleetBind.setCreator(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
            	fleetBindMapper.insert(fleetBind);
				// 添加日志
				FleetBindLog fleetBindLog = new FleetBindLog();
				BeanUtils.copyProperties(fleetBind, fleetBindLog);
				iFleetBindLogService.insert(fleetBindLog);
            }else {
            	// 存在只有一条,修改
            	for (FleetBind fleetBind : fleetBinds) {
            		// 车队修改进行关系修改,入口是资源入口所以资源不变
            		if(!fleetBind.getFleetId().equals(fleetId)) {
            			// 记录日志
            			FleetBindLog fleetBindLog = new FleetBindLog();
            			BeanUtils.copyProperties(fleetBind, fleetBindLog, "id","gmtCreate");
            			fleetBindLogService.insert(fleetBindLog);
            			// 修改
            			fleetBind.setFleetId(fleetId);
//            			fleetBind.setResourceId(carrierInfo.getId());
            			fleetBindMapper.updateById(fleetBind);
            		}
    			}
    		}
    		return carrierInfoNew;
			
    	} catch (BaseException e) {
            LOGGER.error("FleetDriverServiceImpl.updateCarrier" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("FleetDriverServiceImpl.updateCarrier" + e.getMessage());
            throw new BaseException("牵引车信息保存失败");
        }
    	
	}


	/**
	 * 获取车队挂车列表
	 */
	@Override
	public Page<Map<String, Object>> trailerInfoLine(Page<TrailerInfoLineBO> page, String authorization) {
		
		Map<String,Object> condition = page.getCondition();
		if(null == condition) return null;
		
		//  车队id切割成集合
		String fleetId = (String)condition.get("fleetId"); 
		if(StringUtils.isEmpty(fleetId)) return null;

		List<String> fleetIds = Arrays.asList(fleetId.split(","));
		condition.put("fleetIds", fleetIds);
		
		Page<Map<String,Object>> pageVo = new Page<>();
		BeanUtils.copyProperties(page, pageVo);
		
		List<Map<String,Object>> list = fleetDriverMapper.selectTrailerInfo(condition,pageVo);
		list.forEach(carrierInfoLineVO -> {
            if (!Strings.isNullOrEmpty((String)carrierInfoLineVO.get("creator"))) {
                AccountVO accountVO = uaaUtil.getAccountById((String)carrierInfoLineVO.get("creator"), authorization);
                if (Objects.nonNull(accountVO)) {
                    carrierInfoLineVO.put("creator",accountVO.getIdentifier());
                }
            }
        });
	    pageVo.setRecords(list);
	    
	    return pageVo;
	}

	/**
     * 车队添加或修改挂车
     */
    @Transactional
	@Override
	public TrailerInfo updateTrailer(TrailerInfo trailerInfoParam) {
		try {
			Long fleetId = trailerInfoParam.getFleetId();
			trailerInfoParam.setFleetId(null);
			TrailerInfo trailerInfo = trailerInfoService.updateTrailer(trailerInfoParam);
        	// 添加车队与挂车关系
            if(Objects.isNull(fleetId)) throw new BaseException("车队不能为空！");
            
            Wrapper<FleetBind> wrapper = new EntityWrapper<>();
            wrapper.eq("fleet_id", fleetId).eq("resource_id", trailerInfo.getId());
            
            List<FleetBind> fleetBinds = fleetBindMapper.selectList(wrapper);
            
            if(fleetBinds.size() > 1) throw new BaseException("车队与该挂车关系存在多条！");
            // 不存在添加
            if(fleetBinds.size() == 0) {
            	FleetBind fleetBind = new FleetBind();
            	fleetBind.setFleetId(fleetId);
            	fleetBind.setResourceId(trailerInfo.getId());
            	fleetBind.setResourceType(FleetResourcesEnum.TRAILER.getCode());
				fleetBind.setGmtCreate(new Date());
				fleetBind.setGmtModify(new Date());
            	fleetBind.setCreator(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
            	
            	fleetBindMapper.insert(fleetBind);
				// 添加日志
				FleetBindLog fleetBindLog = new FleetBindLog();
				BeanUtils.copyProperties(fleetBind, fleetBindLog);
				iFleetBindLogService.insert(fleetBindLog);
            }else {
            	// 存在只有一条,修改
            	for (FleetBind fleetBind : fleetBinds) {
            		// 车队修改进行关系修改,入口是资源入口所以资源不变
            		if(!fleetBind.getFleetId().equals(fleetId)) {
            			// 记录日志
            			FleetBindLog fleetBindLog = new FleetBindLog();
            			BeanUtils.copyProperties(fleetBind, fleetBindLog, "id","gmtCreate");
            			fleetBindLogService.insert(fleetBindLog);
            			// 修改
            			fleetBind.setFleetId(fleetId);
//            			fleetBind.setResourceId(trailerInfo.getId());
            			fleetBindMapper.updateById(fleetBind);
            		}
    			}
    		}
    		return trailerInfo;
			
    	} catch (BaseException e) {
            LOGGER.error("FleetDriverServiceImpl.updateTrailer" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("FleetDriverServiceImpl.updateTrailer" + e.getMessage());
            throw new BaseException("挂车信息保存失败");
        }
	}

	

}
